#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>        // close()
#include <arpa/inet.h>     // inet_ntoa()
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT   8080
#define BUFFSIZE 1024

int main(){
    //1. 创建socket
    int server_fd = socket(AF_INET, SOCK_DGRAM,0);
    //2. bind socket
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);
    addr.sin_addr.s_addr = INADDR_ANY;
    int res = bind(server_fd,(struct sockaddr *)&addr, sizeof(addr));
    if(res<0){
        perror("bind error");
        exit(1);
    }

    //3. recvfrom/sendto
    //因为是udp，所以不需要建立连接，端对端的发送和接受
    while(1){
        struct sockaddr_in  client_addr;
        int len = sizeof(client_addr);
        memset(&client_addr, 0, len);
        char buff[BUFFSIZE]={0};
        int recv_len = recvfrom(server_fd,buff, BUFFSIZE-1, 0, (struct sockaddr*)&client_addr,
        &len);
        if(recv_len<0){
            perror("recvfrom error");
            continue;
        }

        //打印收到的对端地址的信息
        printf("recv from %s:%d: msg is %s\n", inet_ntoa(client_addr.sin_addr), 
        ntohs(client_addr.sin_port),buff);

        char buff2[1024]={0};
        snprintf(buff2, 1024,"server receive: %s\n", buff);
        //发送给对端
        int send_len = sendto(server_fd, buff2, strlen(buff2), 0, 
        (struct sockaddr*)&client_addr, len);

        if(send_len<0){
            perror("sendto error");
            continue;
        }
    }
    
    close(server_fd);
    return 0;
}